import React, { Component } from 'react'

function Hello(props) {
  return <h2>{props.message}</h2>
}

export class App extends Component {
  constructor() {
    super()

    this.state = {
      message: 'Hello World',
      counter: 0,
    }
  }

  changeText() {
    this.setState({ message: '你好' })
    console.log(this.state.message)
  }

  increment() {
    // 批量处理
    /* this.setState({
      counter: this.state.counter + 1,
    })

    this.setState({
      counter: this.state.counter + 2,
    })

    this.setState({
      counter: this.state.counter + 3,
    }) */

    this.setState((state) => {
      // 从回调函数参数中拿到最新的state
      return {
        counter: state.counter + 1,
      }
    })

    this.setState((state) => {
      return {
        counter: state.counter + 2,
      }
    })

    this.setState((state) => {
      return {
        counter: state.counter + 3,
      }
    })
  }

  render() {
    const { message, counter } = this.state

    return (
      <div>
        <h2>message: {message}</h2>
        <button onClick={() => this.changeText()}>修改文本</button>
        <h2>当前计数：{counter}</h2>
        <button onClick={() => this.increment()}>+1</button>

        <Hello message={message} />
      </div>
    )
  }
}

export default App
